#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   api.py
@Time    :   2023/11/17 11:40:02
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from typing import List
from django.shortcuts import get_object_or_404
from ninja import Router, Field, Query, Schema, ModelSchema
from ninja.pagination import paginate
from utils.ninja import MyPagination
from utils.crud import retrieve
from system.models import Api

router = Router()


class Filters(Schema):
  desc: str = Field(None, alias="desc")
  id: str = Field(None, alias="id")

  
class ApiSchemaIn(ModelSchema):
  class Config:
    model = Api
    model_exclude = ["id","update_time", "create_time"]

  
class ApiSchemaOut(ModelSchema):
  class Config:
    model = Api
    model_fields = "__all__"

  
# 获取api列表
@router.get("/api", response=List[ApiSchemaOut])
@paginate(MyPagination)
def list_api(request, filters: Filters = Query(...)):
  query_set = retrieve(request, Api, filters)
  return query_set

# 通过id获取api
@router.get("/api/{id}", response=ApiSchemaOut)
def get_api_by_id(request, id: int):
  """
  通过id获取API

  Args:
      request: 请求对象
      id: API的id

  Returns:
      返回API对象
  """
  query = Api.objects.filter(id=id).first()
  return query

  
@router.post("/api", response=ApiSchemaOut)
def creat_api(request, data: ApiSchemaIn):
    """
    创建API

    Args:
        request: 请求对象
        data: API数据,类型为ApiSchemaIn

    Returns:
        返回创建的API对象
    """
    if not isinstance(data, dict):
        data = data.dict()
    query = Api.objects.create(**data)
    return query

  
@router.put("/api/{id}", response=ApiSchemaOut)
def put_api(request, id: int, data: ApiSchemaIn):
  # 将请求数据转换为字典形式
  dict_data = data.dict()
  # 根据id获取Api对象，如果找不到则返回404错误
  instance = get_object_or_404(Api, id=id)
  # 遍历字典的键值对，并将属性赋值给Api对象
  for attr, value in dict_data.items():
    setattr(instance, attr, value)
  # 保存修改后的Api对象
  instance.save()
  # 返回修改后的Api对象
  return instance

  
@router.delete("/api/{id}")
def delete_api(request, id: int):
  """
  根据给定的id删除Api对象
  :param request: 请求对象
  :param id: 要删除的Api对象的id
  :return: 返回删除成功的字典
  """
  instance = get_object_or_404(Api, id=id)
  instance.delete()
  return {"success": True}